// sse-worker.ts
self.onmessage = async function (event) {
    const { url, headers } = event.data;

    if (url && headers) {
        const controller = new AbortController();
        const signal = controller.signal;

        try {
            const fetchHeaders = new Headers();
            Object.entries(headers).forEach(([key, value]) => {
                fetchHeaders.append(key, value + "");
            });

            const response = await fetch(url, { headers: fetchHeaders, signal });
            if (!response.ok || response.body === null) {
                throw new Error('Network response was not ok.');
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            let result = '';
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                result += decoder.decode(value, { stream: true });
                processSSE(result);
            }
        } catch (error) {
            postMessage({ error: true, message: error });
        }

        self.onmessage = function (event) {
            if (event.data === 'close') {
                controller.abort();
                self.close(); // Close the worker itself
            }
        };
    }
};

function processSSE(data: string) {
    const events = data.split('\n\n');
    for (let event of events) {
        if (event.trim()) {
            postMessage({ message: event.trim() });
        }
    }
}
